package com.aptemo.webetek.server;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aptemo.webetek.client.enums.EnumBetStatus;
import com.aptemo.webetek.client.enums.EnumPaymentType;
import com.aptemo.webetek.client.enums.EnumPickStatus;
import com.aptemo.webetek.server.data.PMF;
import com.aptemo.webetek.server.data.Payment;
import com.aptemo.webetek.server.data.Pick;
import com.aptemo.webetek.server.data.Stake;
import com.aptemo.webetek.server.data.WebetekUser;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;

public class UpdateStakesWorker
		extends HttpServlet
{

	/**
	 * 
	 */
	private static final long	serialVersionUID	= -5412254594812751972L;

	private static final Logger	log					= Logger.getLogger(UpdateStakesWorker.class.getName());

	// private final MemcacheService memcache =
	// MemcacheServiceFactory.getMemcacheService();
	// private static final String STAKES_PREFIX = "STAKES/";

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		String teamId = req.getParameter("key");
		Key teamKey = KeyFactory.stringToKey(teamId);

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{

			// TODO: query by open stakes
			Query query = pm.newQuery(Stake.class);
			query.setFilter("status == :p1 && parentKey.contains(:p2)");
			List<Stake> stakes = (List<Stake>) query.execute(EnumBetStatus.OPENED, teamKey);

			for (Stake stake : stakes)
			{
				boolean stakeIncomplete = false;
				double earnings = 0.0;

				List<Key> keys = stake.getPickKeys();

				int wonCnt = 0;
				for (Key key : keys)
				{
					Pick pick = pm.getObjectById(Pick.class, key);
					if (pick.getStatus() == EnumPickStatus.NONE)
					{
						// not all bets (picks) closed...
						// reset earnings...
						stake.setEarnings(0.0);
						stakeIncomplete = true;
						break;
					}

					if (pick.getStatus() == EnumPickStatus.WON)
					{
						earnings += pick.getOdds() * stake.getAmount();
						wonCnt++;
					}

				}
				if (stakeIncomplete == false)
				{
					// update stake
					stake.setStatus(EnumBetStatus.CLOSED);

					if (Double.isInfinite(earnings) || Double.isNaN(earnings) || earnings < 0)
					{
						log.severe("Wrong Stake earnings calculation!!! amount=" + stake.getAmount());
					}
					else
					{
						stake.setWonCnt(wonCnt);
						stake.setEarnings(earnings);
						// update user balance & earnings...
						if (true)
						{
							WebetekUser user = pm.getObjectById(WebetekUser.class, stake.getId().getParent());

							Payment payment = new Payment(earnings, "Earnings calculation (balance=" + user.getBalance() + ")", EnumPaymentType.EARNINGS);
							user.addPayment(payment);

							// some stats...
							user.updateAllBetCount(keys.size());
							user.updateWonBetsCount(wonCnt);
						}
					}
				}

				// start statistics task...
				// createUserStatisticsTask(user.getSid());
			}

			// cache...
			// memcache.put(STATS_PREFIX + userId, stats);
		}
		finally
		{
			pm.close();
		}

	}

	private void createUserStatisticsTask(String id)
	{
		Queue queue = QueueFactory.getQueue("background-processing");
		queue.add(TaskOptions.Builder.url("/workers/userStatistics").param("key", id));
	}

}
